import { showNotification } from '@/utils/notify';
import request from '@/utils/request';
import { defineStore } from 'pinia';
import { ref } from 'vue';

type User = {
    username: string,
    userId: string,
    password: string,
    role: string
}

type UserPage = {
    code: number, 
    message: string,
    data: {
        records: User[],
        total: number,
        size: number, 
    }
}   

export const useSysUserStore = defineStore('sysUser', () => {
    const sysUsers = ref<User[]>([]);
    const total = ref(0); // 总课程数量
    const currentPage = ref(1); // 当前页码
    const pageSize = ref(10); // 每页显示的课程数量


    const addSysUser = async(sysUser: User) => {
        const { code, data } = await request.post<{ code: number; data: object }>('/api/user/add', sysUser);
        if (code === 200) {
            showNotification("用户添加成功", false);
            fetchSysUsers()

        } else {
            showNotification("用户添加失败", true);
        }
    };

    const updateSysUser = async(index: number, updatedSysUser: User) => {
        try {
            const userId = updatedSysUser.userId;
            const { code, data } = await request.post<{ code: number; data: object }>(
                `/api/user/update/${userId}`,
                updatedSysUser
            );
            if (code === 200) {
                showNotification("用户更新成功", false);
                fetchSysUsers()

            } else {
                showNotification("用户更新失败", true);
            }
        } catch (error) {
            showNotification("用户更新失败", true);
        }
    };

    const deleteSysUser = async(index: number) => {
        try {
            const userId = sysUsers.value[index].userId;
            const { code, data } = await request.post<{ code: number; data: object }>(
                `/api/users/remove/${userId}`
            );
            if (code === 200) {
                showNotification("用户删除成功", false);
                fetchSysUsers(); 
            } else {
               showNotification("用户删除失败", true);
            }
            fetchSysUsers()

        } catch (error) {
            showNotification("用户删除成功", true);
        }
    };

   
    const changePage = (page: number) => {
        currentPage.value = page; // 更新当前页码
        fetchSysUsers(); 
    };

    const fetchSysUsers = async () => {
        try {
            const { data } = await request.get<UserPage>(
                `/api/user/page?current=${currentPage.value}&size=${pageSize.value}`
            );
            sysUsers.value = data.records;
            total.value = data.total;
           showNotification( '获取用户信息成功',false); 

        } catch (error) {
           showNotification( '获取用户信息失败',true); 
        }
    }


    onMounted(() => {
        fetchSysUsers(); // 初始加载第一页 
    })

    return {
        sysUsers,
        addSysUser,
        updateSysUser,
        deleteSysUser,
        changePage,
        currentPage,
        pageSize,
        total

    };
});